package com.nova.edc.service.collect.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.nova.edc.model.energy.CollectData;
import com.nova.edc.model.energy.Summary;
import com.nova.edc.service.collect.CloudConstant;
import com.nova.edc.service.collect.CloudDataService;
import com.nova.edc.service.energy.CollectDataService;
import com.nova.frame.utils.DateUtils;
import com.nova.frame.utils.StringUtils;
import com.seio.edc.util.AssitDateUtil;
import com.seio.edc.util.StringUtil;

public class CloudDataServiceImpl implements CloudDataService {

	@Autowired
	private CollectDataService novaCollectDataService;

	@Value("#{cloudDataProperties['url']}")
	private String url;

	@Override
	public String getXmlByDatetime(String gateway, String startTime,
			String endTime) {
		String xml = "";
		RPCServiceClient serviceClient = null;
		try {
			serviceClient = new RPCServiceClient();
			Options options = serviceClient.getOptions();
			EndpointReference targetEPR = new EndpointReference(url);
			options.setTo(targetEPR);
			options.setTimeOutInMilliSeconds(200000);// 连接超时时间设定200秒
			QName opAddEntry = new QName(CloudConstant.QNAME,
					CloudConstant.METHOD);
			Object[] opAddEntryArgs = new Object[] { CloudConstant.USERNAME,
					CloudConstant.PASSWORD, gateway, startTime, endTime };
			xml = (String) serviceClient.invokeBlocking(opAddEntry,
					opAddEntryArgs, new Class[] { String.class })[0];
		} catch (AxisFault e) {
			e.printStackTrace();
		}
		return xml;
	}

	@Override
	public List<CollectData> parseXml(String xml) {

		List<CollectData> collectDataList = new ArrayList<CollectData>();
		if (!StringUtil.isEmpty(xml)) {
			try {
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder builder = dbf.newDocumentBuilder();
				InputStream inputStream = new ByteArrayInputStream(
						xml.getBytes());
				Document doc = builder.parse(inputStream);
				Element root = (Element) doc.getDocumentElement();
				NodeList nodelist = root.getChildNodes();
				int size = nodelist.getLength();
				for (int i = 0; i < size; i++) {
					Node node = nodelist.item(i);
					if (node.getNodeType() == Node.ELEMENT_NODE) {
						Element elementNode = (Element) node;
						String content = elementNode.getTextContent();
						String activeTime = StringUtil.getMidString(content,
								"data_time", "gateway_logo");
						String gatewayID = StringUtil.getMidString(content,
								"gateway_logo", "sensor_name");
						String sensorID = StringUtil.getMidString(content,
								"sensor_name", "channel_name");
						String channelID = StringUtil.getMidString(content,
								"channel_name", "value");
						String activeState = StringUtil.getMidString(content,
								"value", "").substring(0, 1);

						// 原始数据保存在T_CollectData表中
						CollectData collectData = new CollectData();
						collectData.setActivetime(DateUtils
								.getStr2LDate(activeTime));
						collectData.setAdddate(DateUtils
								.getStr2LDate(activeTime));
						collectData.setGatewayid(gatewayID);
						collectData.setSensorid(StringUtils
								.isNotNullOrEmpty(sensorID) ? Integer
								.parseInt(sensorID) : 0);
						collectData.setChannelid(StringUtils
								.isNotNullOrEmpty(channelID) ? Integer
								.parseInt(channelID) : 0);
						collectData.setActivestate(activeState);
						collectData.setActivecount(1);
						if (collectDataList.size() == 0) {
							collectDataList.add(collectData);
						} else if (collectDataList.contains(collectData)) {
							int location = collectDataList
									.lastIndexOf(collectData);
							CollectData temp = collectDataList.get(location);
							if (temp.getActivestate().equals(
									collectData.getActivestate())) {
								String startDate = DateUtils.getDate2MStr(temp
										.getAdddate());
								String endDate = DateUtils
										.getDate2MStr(collectData
												.getActivetime());
								if (!startDate.equals(endDate)) {
									int span = AssitDateUtil.getSpanMinute(
											startDate, endDate);
									if (span > 1) {
										if (temp.getActivecount() < 20) {
											temp.setActivecount(temp
													.getActivecount()
													+ span
													- 1);
										}
									}
									temp.setAdddate(collectData.getActivetime());
									if (temp.getActivecount() < 20) {
										temp.setActivecount(temp
												.getActivecount() + 1);
									}
									collectDataList.set(location, temp);
								}
							} else {
								collectDataList.add(collectData);
							}
						} else {
							collectDataList.add(collectData);
						}
					}
				}
				novaCollectDataService.wrapCollectData(collectDataList);
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return collectDataList;
	}

	@Override
	public List<Summary> parseSummary(String gateway, String startTime,
			String endTime) {
		List<Summary> summaries = novaCollectDataService.summaryCollectData(
				gateway, startTime, endTime);
		return summaries;
	}
}
